package com.jie.component.filter.core;

import cn.hutool.core.util.StrUtil;
import com.jie.common.util.BaseParameterHolder;
import com.jie.common.util.InputStreamUtil;
import com.jie.common.util.LogUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

import static com.jie.common.constant.StrConst.*;

/**
 * @author jie
 * @version 1.0 2025-02-12 业务参数过滤器
 */
@Slf4j
public class BaseParameterFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {
        // 读取请求体
        ServletInputStream sis = request.getInputStream();
        String requestBody  = InputStreamUtil.inputStreamConvertString(sis);
        // 格式化请求体，方便日志输出
        if (StrUtil.isNotBlank(requestBody)) {
            requestBody = requestBody.replaceAll(" ", "").replaceAll("\r\n","");
        }

        String traceId = request.getHeader(TRACE_ID);
        String gray = request.getHeader(GRAY_PARAMETER);
        String userId = request.getHeader(USER_ID);

        try {
            if (StrUtil.isNotBlank(traceId)) {
                BaseParameterHolder.setParameter(TRACE_ID,traceId);
                MDC.put(TRACE_ID,traceId);
            }

            if (StrUtil.isNotBlank(gray)) {
                BaseParameterHolder.setParameter(GRAY_PARAMETER,gray);
                MDC.put(GRAY_PARAMETER,gray);
            }

            if (StrUtil.isNotBlank(userId)) {
                BaseParameterHolder.setParameter(USER_ID,userId);
                MDC.put(USER_ID,userId);
            }

            LogUtil.requestLog(request.getRequestURI(), requestBody, userId);
            filterChain.doFilter(request, response);
        } finally {
            BaseParameterHolder.removeParameter(TRACE_ID);
            MDC.remove(TRACE_ID);
            BaseParameterHolder.removeParameter(GRAY_PARAMETER);
            MDC.remove(GRAY_PARAMETER);
            BaseParameterHolder.removeParameter(USER_ID);
            MDC.remove(USER_ID);
            BaseParameterHolder.removeParameter(CODE);
            MDC.remove(CODE);
        }
    }

}
